import axios from 'axios'
import router from '../router/index.js'
const instance = axios.create({
    timeout: 4000
});
// Add a request interceptor
instance.interceptors.request.use(function(config) {
    // Do something before request is sent
    // console.log(config.headers)
    // console.log(instance.defaults.headers)
    let token = localStorage.getItem('token')
    if (token) {
        // instance.defaults.headers.common['Authorization'] = `Bearer ${token}`
        /*思考：instance上写headers和config的区别*/
        config.headers['Authorization'] =`Bearer ${token}`
        // console.log(config.headers)
    }
    return config;
}, function(error) {
    // Do something with request error
    console.log(error)
    return Promise.reject(error);
});

// Add a response interceptor
instance.interceptors.response.use(function(response) {
    // Do something with response data
    if (response.data.token) {
        localStorage.setItem('token', response.data.token)
    }
    return response;
}, function(error) {
    // Do something with response error
    if (error.response.status == 401) {
        localStorage.removeItem('token');
          return router.push('/About')
        //ruturn的原因（如果不return，报错：Uncaught (in promise)）
        //axois请求未指定catch回调函数
    }
    console.log(error)//前面return了这里不执行
    return Promise.reject(error);
});
export default instance;